<template>
  <div class="maintenance-strategy">
    <el-card class="box-card">
      <div class="header-bar">
        <el-select v-model="selectedGroup" placeholder="分组包含" style="width: 180px; margin-right: 10px;">
          <el-option v-for="group in groupList" :key="group" :label="group" :value="group" />
        </el-select>
        <el-select v-model="selectedType" placeholder="分类包含" style="width: 180px; margin-right: 10px;">
          <el-option v-for="type in typeList" :key="type" :label="type" :value="type" />
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="openEditDialog()">新建</el-button>
        <el-button type="warning" icon="el-icon-edit" :disabled="!selectedRow" @click="openEditDialog(selectedRow)">修改</el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="!selectedRow" @click="deleteRow">删除</el-button>
        <el-button type="primary" @click="openBatchDialog">批量配置阈值</el-button>
        <el-button type="success" @click="openCustomDialog">自定义策略</el-button>
      </div>
      <el-table
        :data="filteredDevices"
        style="width: 100%; margin-top: 15px;"
        @row-click="handleRowClick"
        :row-class-name="rowClassName"
        highlight-current-row
        :current-row-key="selectedRow ? selectedRow.id : null"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="序号" width="60" />
        <el-table-column prop="group" label="分组" width="120" />
        <el-table-column prop="type" label="分类" width="120" />
        <el-table-column prop="name" label="设备名称" width="160" />
        <el-table-column prop="importance" label="重要性" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.importance === '关键产线设备' ? 'danger' : 'info'">{{ scope.row.importance }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="health" label="健康度" width="100">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.health" :status="scope.row.health < getThreshold(scope.row) ? 'exception' : 'success'" :text-inside="true" :stroke-width="18" />
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="阈值" width="80">
          <template slot-scope="scope">
            <span>{{ getThreshold(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cycle" label="维护周期" width="140">
          <template slot-scope="scope">
            <span>{{ scope.row.cycle }} 小时</span>
          </template>
        </el-table-column>
        <el-table-column prop="spare" label="备件策略" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.spareType }}库存≥{{ scope.row.spareCount }}件</span>
          </template>
        </el-table-column>
        <el-table-column prop="paramLink" label="参数异常联动" width="160">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.paramLink" @change="saveDevices" />
            <span v-if="scope.row.paramLink" style="margin-left: 8px; color: #409EFF; cursor: pointer;" @click.stop="openParamDialog(scope.row)">设置</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="mini" @click.stop="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click.stop="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新建策略弹窗 -->
    <el-dialog :title="editForm.id ? '修改策略' : '新建策略'" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="110px">
        <el-form-item label="分组" prop="group">
          <el-select v-model="editForm.group" placeholder="请选择分组">
            <el-option v-for="group in groupList" :key="group" :label="group" :value="group" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择分类">
            <el-option v-for="type in typeList" :key="type" :label="type" :value="type" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="重要性" prop="importance">
          <el-radio-group v-model="editForm.importance">
            <el-radio label="关键产线设备" />
            <el-radio label="辅助设备" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="健康度" prop="health">
          <el-input-number v-model="editForm.health" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="维护周期(小时)" prop="cycle">
          <el-input-number v-model="editForm.cycle" :min="100" :max="10000" />
        </el-form-item>
        <el-form-item label="备件类型" prop="spareType">
          <el-select v-model="editForm.spareType" placeholder="请选择备件类型">
            <el-option label="关键备件" value="关键备件" />
            <el-option label="普通备件" value="普通备件" />
          </el-select>
        </el-form-item>
        <el-form-item label="备件库存阈值" prop="spareCount">
          <el-input-number v-model="editForm.spareCount" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="参数异常联动">
          <el-switch v-model="editForm.paramLink" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 批量配置阈值弹窗 -->
    <el-dialog title="批量配置阈值" :visible.sync="batchDialogVisible" width="400px">
      <el-form :model="batchForm" label-width="120px">
        <el-form-item label="分组">
          <el-select v-model="batchForm.group" placeholder="请选择分组">
            <el-option v-for="group in groupList" :key="group" :label="group" :value="group" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="batchForm.type" placeholder="请选择分类">
            <el-option v-for="type in typeList" :key="type" :label="type" :value="type" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键产线设备阈值">
          <el-input-number v-model="batchForm.criticalThreshold" :min="10" :max="100" />
        </el-form-item>
        <el-form-item label="辅助设备阈值">
          <el-input-number v-model="batchForm.auxThreshold" :min="10" :max="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBatch">确定</el-button>
      </div>
    </el-dialog>

    <!-- 自定义策略弹窗 -->
    <el-dialog title="自定义策略" :visible.sync="customDialogVisible" width="500px">
      <el-form :model="customForm" label-width="120px">
        <el-form-item label="设备名称">
          <el-select v-model="customForm.deviceId" placeholder="请选择设备">
            <el-option v-for="dev in devices" :key="dev.id" :label="dev.name" :value="dev.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="维护周期(小时)">
          <el-input-number v-model="customForm.cycle" :min="100" :max="10000" />
        </el-form-item>
        <el-form-item label="备件类型">
          <el-select v-model="customForm.spareType" placeholder="请选择备件类型">
            <el-option label="关键备件" value="关键备件" />
            <el-option label="普通备件" value="普通备件" />
          </el-select>
        </el-form-item>
        <el-form-item label="备件库存阈值">
          <el-input-number v-model="customForm.spareCount" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="参数异常联动">
          <el-switch v-model="customForm.paramLink" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCustom">确定</el-button>
      </div>
    </el-dialog>

    <!-- 参数异常联动设置弹窗 -->
    <el-dialog title="参数异常联动设置" :visible.sync="paramDialogVisible" width="400px">
      <el-form :model="paramForm" label-width="140px">
        <el-form-item label="振动阈值(%)">
          <el-input-number v-model="paramForm.vibrationThreshold" :min="100" :max="300" />
        </el-form-item>
        <el-form-item label="超阈缩短周期(%)">
          <el-input-number v-model="paramForm.cycleShorten" :min="10" :max="100" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="paramDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveParam">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MaintenanceStrategy',
  data() {
    return {
      groupList: ['产线A', '产线B', '产线C'],
      typeList: ['主轴', '电机', '传感器', '泵'],
      devices: [],
      selectedGroup: '',
      selectedType: '',
      selectedRow: null,
      editDialogVisible: false,
      editForm: {
        id: '', group: '', type: '', name: '', importance: '关键产线设备', health: 100, cycle: 2000, spareType: '关键备件', spareCount: 3, paramLink: false
      },
      editRules: {
        group: [{ required: true, message: '请选择分组', trigger: 'change' }],
        type: [{ required: true, message: '请选择分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        importance: [{ required: true, message: '请选择重要性', trigger: 'change' }],
        health: [{ required: true, message: '请输入健康度', trigger: 'blur' }],
        cycle: [{ required: true, message: '请输入维护周期', trigger: 'blur' }],
        spareType: [{ required: true, message: '请选择备件类型', trigger: 'change' }],
        spareCount: [{ required: true, message: '请输入库存阈值', trigger: 'blur' }],
      },
      batchDialogVisible: false,
      batchForm: {
        group: '',
        type: '',
        criticalThreshold: 60,
        auxThreshold: 40
      },
      customDialogVisible: false,
      customForm: {
        deviceId: '',
        cycle: 2000,
        spareType: '关键备件',
        spareCount: 3,
        paramLink: false
      },
      paramDialogVisible: false,
      paramForm: {
        id: '',
        vibrationThreshold: 150,
        cycleShorten: 50
      },
      thresholds: {
        // { group, type, critical, aux }
      }
    }
  },
  computed: {
    filteredDevices() {
      let list = this.devices
      if (this.selectedGroup) list = list.filter(d => d.group === this.selectedGroup)
      if (this.selectedType) list = list.filter(d => d.type === this.selectedType)
      return list
    }
  },
  created() {
    this.loadDevices()
    this.loadThresholds()
  },
  methods: {
    // mock数据初始化
    getDefaultDevices() {
      return [
        { id: 1, group: '产线A', type: '主轴', name: '主轴轴承1', importance: '关键产线设备', health: 58, cycle: 2000, spareType: '关键备件', spareCount: 3, paramLink: true, paramConfig: { vibrationThreshold: 150, cycleShorten: 50 } },
        { id: 2, group: '产线A', type: '电机', name: '主电机', importance: '辅助设备', health: 45, cycle: 3000, spareType: '普通备件', spareCount: 5, paramLink: false },
        { id: 3, group: '产线B', type: '泵', name: '冷却泵', importance: '关键产线设备', health: 70, cycle: 2500, spareType: '关键备件', spareCount: 4, paramLink: false },
        { id: 4, group: '产线C', type: '传感器', name: '温度传感器', importance: '辅助设备', health: 38, cycle: 4000, spareType: '普通备件', spareCount: 2, paramLink: false },
      ]
    },
    loadDevices() {
      const data = localStorage.getItem('maintenance_devices')
      if (data) {
        this.devices = JSON.parse(data)
      } else {
        this.devices = this.getDefaultDevices()
        this.saveDevices()
      }
    },
    saveDevices() {
      localStorage.setItem('maintenance_devices', JSON.stringify(this.devices))
    },
    loadThresholds() {
      const data = localStorage.getItem('maintenance_thresholds')
      if (data) {
        this.thresholds = JSON.parse(data)
      } else {
        this.thresholds = {}
      }
    },
    saveThresholds() {
      localStorage.setItem('maintenance_thresholds', JSON.stringify(this.thresholds))
    },
    getThreshold(row) {
      // 优先设备独立设置，其次分组/类型批量设置，否则默认
      if (row.threshold) return row.threshold
      const key = `${row.group}_${row.type}`
      if (this.thresholds[key]) {
        return row.importance === '关键产线设备' ? this.thresholds[key].critical : this.thresholds[key].aux
      }
      return row.importance === '关键产线设备' ? 60 : 40
    },
    handleRowClick(row) {
      this.selectedRow = row
    },
    rowClassName({ row }) {
      return row.health < this.getThreshold(row) ? 'row-warning' : ''
    },
    openEditDialog(row) {
      if (row) {
        this.editForm = { ...row }
      } else {
        this.editForm = { id: '', group: '', type: '', name: '', importance: '关键产线设备', health: 100, cycle: 2000, spareType: '关键备件', spareCount: 3, paramLink: false }
      }
      this.editDialogVisible = true
    },
    saveEdit() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return
        if (this.editForm.id) {
          // 修改
          const idx = this.devices.findIndex(d => d.id === this.editForm.id)
          if (idx !== -1) {
            this.devices.splice(idx, 1, { ...this.editForm })
          }
        } else {
          // 新建
          this.editForm.id = Date.now()
          this.devices.push({ ...this.editForm })
        }
        this.saveDevices()
        this.editDialogVisible = false
        this.selectedRow = null
        this.$message.success('保存成功')
      })
    },
    deleteRow(row) {
      const target = row || this.selectedRow
      if (!target) return
      this.$confirm('确定要删除该设备策略吗？', '提示', { type: 'warning' })
        .then(() => {
          this.devices = this.devices.filter(d => d.id !== target.id)
          this.saveDevices()
          this.selectedRow = null
          this.$message.success('删除成功')
        })
    },
    openBatchDialog() {
      this.batchForm = { group: '', type: '', criticalThreshold: 60, auxThreshold: 40 }
      this.batchDialogVisible = true
    },
    saveBatch() {
      if (!this.batchForm.group || !this.batchForm.type) {
        this.$message.error('请选择分组和分类')
        return
      }
      const key = `${this.batchForm.group}_${this.batchForm.type}`
      this.thresholds[key] = {
        critical: this.batchForm.criticalThreshold,
        aux: this.batchForm.auxThreshold
      }
      this.saveThresholds()
      this.batchDialogVisible = false
      this.$message.success('批量阈值配置成功')
    },
    openCustomDialog() {
      this.customForm = { deviceId: '', cycle: 2000, spareType: '关键备件', spareCount: 3, paramLink: false }
      this.customDialogVisible = true
    },
    saveCustom() {
      const dev = this.devices.find(d => d.id === this.customForm.deviceId)
      if (!dev) {
        this.$message.error('请选择设备')
        return
      }
      dev.cycle = this.customForm.cycle
      dev.spareType = this.customForm.spareType
      dev.spareCount = this.customForm.spareCount
      dev.paramLink = this.customForm.paramLink
      this.saveDevices()
      this.customDialogVisible = false
      this.$message.success('自定义策略已保存')
    },
    openParamDialog(row) {
      this.paramForm = {
        id: row.id,
        vibrationThreshold: row.paramConfig ? row.paramConfig.vibrationThreshold : 150,
        cycleShorten: row.paramConfig ? row.paramConfig.cycleShorten : 50
      }
      this.paramDialogVisible = true
    },
    saveParam() {
      const dev = this.devices.find(d => d.id === this.paramForm.id)
      if (dev) {
        dev.paramConfig = {
          vibrationThreshold: this.paramForm.vibrationThreshold,
          cycleShorten: this.paramForm.cycleShorten
        }
        this.saveDevices()
        this.paramDialogVisible = false
        this.$message.success('参数异常联动设置已保存')
      }
    }
  }
}
</script>

<style scoped>
.maintenance-strategy {
  padding: 20px;
}
.header-bar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.row-warning {
  background: #fffbe6 !important;
}
</style>
